<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isLook ? '详情' : '录入发票信息'" v-model="visible" align-center width="1320px" :z-index="2000"
    @close="handleClose">
    <el-form ref="formRef" :model="form" label-width="0">
      <div class="v-title mb-3">文件信息</div>
      <div class="my-2 flex flex-col">
        <el-form-item prop="contract_list" :rules="[{ validator: validator, trigger: 'change'}]">
          <VUpload v-model="form.contract_list" required multiple edit :params="{ is_origin: 2 }" :types="['jpg', 'jpeg', 'png', 'pdf']" :disabled="isLook"
            title="开票合同" @change="validateField('contract_list')" />
        </el-form-item>
        <el-form-item prop="deliver_list" :rules="[{ validator: validator, trigger: 'change'}]">
          <VUpload v-model="form.deliver_list" required multiple edit :params="{ is_origin: 2 }" :types="['jpg', 'jpeg', 'png', 'pdf']" :disabled="isLook"
            title="送货清单" @change="validateField('deliver_list')" />
        </el-form-item>
        <el-form-item prop="invoice_list" :rules="[{ validator: validator, trigger: 'change'}]">
          <VUpload v-model="form.invoice_list" required multiple edit :params="{ is_origin: 2 }" :types="['jpg', 'jpeg', 'png', 'pdf']" :disabled="isLook"
            title="发票文件" @change="validateField('invoice_list')" />
        </el-form-item>
      </div>

      <div class="v-title mt-4 mb-3">开票信息</div>
      <vxe-table ref="tableRef" :data="form.list" size="mini" :min-height="60" :max-height="560" show-overflow :row-config="{height: 60}">
        <vxe-column type="expand" width="60">
          <template #content="{ row: tableRow, rowIndex: tableRowIndex }">
            <div class="p-2">
              <vxe-table :data="tableRow.invoice" size="mini" :min-height="60" :max-height="560">
                <vxe-column :min-width="120">
                  <template #header>
                    发票代码
                  </template>
                  <template #default="{ row, rowIndex }">
                    <el-form-item :prop="`list.${tableRowIndex}.invoice.${rowIndex}.invoice_code`" class="my-3">
                      <el-input v-model="row.invoice_code" placeholder="发票代码" :disabled="isLook||row?.invoice_status==3" class="w-full" @input="val => (row.invoice_code = val.replace(/[^a-zA-Z0-9]/g, ''))" />
                    </el-form-item>
                  </template>
                </vxe-column>
                <vxe-column :min-width="120">
                  <template #header>
                    <span class="text-red-600">*</span>
                    发票号码
                  </template>
                  <template #default="{ row, rowIndex }">
                    <el-form-item :prop="`list.${tableRowIndex}.invoice.${rowIndex}.invoice_no`" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]" class="my-3">
                      <el-input v-model="row.invoice_no" placeholder="请输入" :disabled="isLook||row?.invoice_status==3" class="w-full" @input="val => (row.invoice_no = val.replace(/[^0-9]/g, ''))" />
                    </el-form-item>
                  </template>
                </vxe-column>
                <vxe-column :min-width="120">
                  <template #header>
                    <span class="text-red-600">*</span>
                    发票数量
                  </template>
                  <template #default="{ row, rowIndex }">
                    <el-form-item :prop="`list.${tableRowIndex}.invoice.${rowIndex}.invoice_num`" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]" class="my-3">
                      <el-input-number v-model="row.invoice_num" controls-position="right" placeholder="发票数量" :min="1" :max="tableRow.billing_num" :step="1" :precision="0" :disabled="isLook||row?.invoice_status==3" class="w-full"
                        @change="val => (row.total_price = XEUtils.toFixed(val * +form.list[0].unit_price, 2))" />
                    </el-form-item>
                  </template>
                </vxe-column>
                <vxe-column :min-width="120">
                  <template #header>
                    <span class="text-red-600">*</span>
                    开票不含税金额
                  </template>
                  <template #default="{ row, rowIndex }">
                    <el-form-item :prop="`list.${tableRowIndex}.invoice.${rowIndex}.invoice_num`" class="my-3">
                      <el-input-number v-model="row.total_price" :controls="false" :disabled="true" placeholder="开票不含税金额" :min="0" :step="0.01" :precision="2" class="w-full" />
                    </el-form-item>
                  </template>
                </vxe-column>
                <vxe-column :min-width="120">
                  <template #header>
                    <span class="text-red-600">*</span>
                    发票行号
                  </template>
                  <template #default="{ row, rowIndex }">
                    <el-form-item :prop="`list.${tableRowIndex}.invoice.${rowIndex}.invoice_line`" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]" class="my-3">
                      <el-input v-model="row.invoice_line" placeholder="发票行号" :disabled="isLook||row?.invoice_status==3" class="w-full" />
                    </el-form-item>
                  </template>
                </vxe-column>
                <vxe-column :min-width="120">
                  <template #header>
                    <span class="text-red-600">*</span>
                    开票日期
                  </template>
                  <template #default="{ row, rowIndex }">
                    <el-form-item :prop="`list.${tableRowIndex}.invoice.${rowIndex}.billing_time`" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]" class="my-3">
                      <el-date-picker v-model="row.billing_time" placeholder="日期选择" type="date" value-format="YYYY-MM-DD" :disabled="isLook||row?.invoice_status==3" class="w-full" />
                    </el-form-item>
                  </template>
                </vxe-column>
                <vxe-column v-if="!isLook" :width="80">
                  <template #header>
                    <el-button link type="primary" @click="add(tableRow)">添加</el-button>
                  </template>
                  <template #default="{row, rowIndex }">
                    <el-button link type="danger" @click="tableRow.invoice.splice(rowIndex, 1)" :disabled="row?.invoice_status==3" class="my-3">删除</el-button>
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
          </template>
        </vxe-column>
        <vxe-column title="供应商" :min-width="120">
          <template #default="{ row }">
            <VText :value="row.supplier_name" line="2" />
          </template>
        </vxe-column>
        <vxe-column title="入库时间" :min-width="100">
          <template #default="{ row }">
            <VText :value="row.inbound_time" line="2" />
          </template>
        </vxe-column>
        <vxe-column title="结算方式" :min-width="120">
          <template #default="{ row }">
            <VText :value="row.period_name" line="2" />
          </template>
        </vxe-column>
        <vxe-column title="部门" field="department_name" :min-width="100">
          <template #default="{ row }">
            <VText :value="row.department_name" line="2" />
          </template>
        </vxe-column>
        <vxe-column title="采购单号" :min-width="140">
          <template #default="{ row }">
            <VText :value="row.purchase_no" />
          </template>
        </vxe-column>
        <vxe-column title="SKU" field="sku" :min-width="80" />
        <vxe-column title="采购人员" field="purchase_user_name" :min-width="120" />
        <vxe-column title="开票品名" field="invoice_name" :min-width="80">
          <template #default="{ row }">
            <VText :value="row.invoice_name" />
          </template>
        </vxe-column>
        <vxe-column title="开票单位" field="invoice_unit" :min-width="80">
          <template #default="{ row }">
            <VText :value="row.invoice_unit" />
          </template>
        </vxe-column>
        <vxe-column title="应开票数量" field="billing_num" :min-width="80" />
        <vxe-column title="已开票数量" field="invoice_num" :min-width="80" />
        <vxe-column title="待开票数量" field="leave_num" :min-width="80" />
        <vxe-column title="实际含税单价" field="billing_unit_price_tax" min-width="90" />
        <vxe-column title="实际含税金额" field="actually_inbound_price_tax" min-width="90" />
        <vxe-column title="开票不含税单价" field="unit_price" min-width="90" />
        <vxe-column title="开票不含税金额" field="total_price" min-width="90" />
        <vxe-column title="供应商含税单价" field="unit_price_tax" min-width="90" />
        <vxe-column title="供应商含税金额" field="supplier_total_price_tax" min-width="90" />
        <vxe-column title="发票税率" field="tax_percent" :min-width="80" />
      </vxe-table>
    </el-form>
    <template v-if="isLook" #footer>
      <el-button @click="close">关 闭</el-button>
    </template>
    <template v-else #footer>
      <el-button @click="close">取 消</el-button>
      <!-- <el-button type="primary" :loading="loadings['submit' + 2]" @click="create(2)">确 定</el-button> -->
      <el-button type="primary" :loading="loadings['submit' + 1]" @click="create(1)">提 交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import XEUtils from 'xe-utils'
import { ElMessage } from 'element-plus'
const props = defineProps({
  api: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})

const validator = (rule, value, cb) => {
  console.log('value', value)
  if (!value || !value.length) {
    cb(new Error('不能为空'))
    return
  }
  cb()
}

const validateField = (field) => {
  formRef.value.validateField(field)
}

const tableRef = ref()
const expandAllEvent = () => {
  const $table = tableRef.value
  if ($table) {
    $table.setAllRowExpand(true)
  }
}

// 打开弹窗
const isLook = ref(false)
const open = async (b_id, row) => {
  isLook.value = !!row
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
  if (row?.i_id) {
    isLook.value = true
    const res = await props.api.detail({ i_id: b_id })
    form.value = { ...res.data, list: [res.data], ...row }
  } else {
    const res = await props.api.detail({ b_id })
    if (!row) {
      res.data.list.forEach(d => {
        const { invoice } = d
        if (!invoice?.length) {
          d.invoice.push({ "invoice_code": null, "invoice_no": null, "invoice_line": invoice.length + 1 })
        }
      })
    }
    form.value = {
      b_id, ...res.data
    }
  }
  nextTick(expandAllEvent)
}

// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

const add = (row) => {
  row.invoice.push({ invoice_code: null, invoice_no: null, invoice_line: `${row.invoice.length + 1}` })
}

// 提交
const create = async (is_submit) => {
  if (!await formRef?.value.validate()) return
  loadings['submit' + is_submit] = true
  form.value.is_submit = is_submit
  props.api.save(form.value).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings['submit' + is_submit] = false
  })
}

defineExpose({ open })
</script>